package com.comprental.utils;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang3.StringUtils;

import java.lang.reflect.Array;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;

/**
 * @Author: zhangjun
 * @Date: 2020/8/18 11:38
 * @Description: 计算 签名
 */
public class SignUtil {

    /**
     * md5加密
     *
     * @param json
     * @param partnerKey
     * @return
     */
    public static String getSign(String json, String partnerKey) {
        JSONObject jsonObject = JSONObject.parseObject(json);
        String params = "";
        Map<String, Object> map = new TreeMap<String, Object>(jsonObject);
        Set<String> keys = map.keySet();
        keys.remove("partner_key");
        for (String key : keys) {
            Object value = jsonObject.get(key);
            if (value instanceof Array || value instanceof JSONArray) continue;
            if (value != null && StringUtils.isNotBlank(String.valueOf(value))) {
                if (StringUtils.isBlank(params)) {
                    params = key + "=" + String.valueOf(value);
                } else {
                    params += "&" + key + "=" + String.valueOf(value);
                }
            }
        }
        params += "&partner_key=" + partnerKey;
        return Md5Util.getMD5String(params);
    }

}
